package com.example.bingobox.service;

import android.app.Service;
import android.content.Intent;
import android.os.Environment;
import android.os.Handler;
import android.os.IBinder;
import android.os.Looper;

import com.example.bingobox.model.State;
import com.example.bingobox.utils.LocationUtils;
import com.google.gson.Gson;

import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;

public class LocationUpdateService extends Service {
    private static final long UPDATE_INTERVAL = 5 * 60 * 1000; // 5分钟更新一次
    private final Handler handler = new Handler(Looper.getMainLooper());
    private final Gson gson = new Gson();
    private final Runnable updateRunnable = new Runnable() {
        @Override
        public void run() {
            updateLocation();
            handler.postDelayed(this, UPDATE_INTERVAL);
        }
    };

    @Override
    public void onCreate() {
        super.onCreate();
        handler.post(updateRunnable);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        handler.removeCallbacks(updateRunnable);
    }

    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    private void updateLocation() {
        LocationUtils.getCurrentLocation(this, new LocationUtils.LocationCallback() {
            @Override
            public void onLocationReceived(State.Location location) {
                updateStateWithLocation(location);
            }

            @Override
            public void onLocationFailed(String error) {
                // 位置更新失败，可以记录日志
            }
        });
    }

    private void updateStateWithLocation(State.Location location) {
        File dataDir = new File(Environment.getExternalStorageDirectory(), "BingoBox/data");
        File stateFile = new File(dataDir, "state.json");

        try {
            State state;
            // 读取当前状态
            try (FileReader reader = new FileReader(stateFile)) {
                state = gson.fromJson(reader, State.class);
            }

            if (state != null) {
                // 更新位置信息
                state.setCurrentCity(location);
                state.setCurrentLocation(location);

                // 保存更新后的状态
                try (FileWriter writer = new FileWriter(stateFile)) {
                    gson.toJson(state, writer);
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
} 